const express = require("express");
const cors=require("cors")
const app = express();
const fs = require("fs");
app.use(cors())
md5 = require("md5");
let preveMd5=null
content=null
newContent={};
// 监听是否有储存过内容
(async()=>{
  try{
    content = await isFileExisted("./content.js")
    console.log(content,'成功1')
    content=require('./content')
  }catch(error){
    content = null
    console.log(error,11111)
  }
})();
// 监听是否与上次修改相同
(async()=>{
  try{
    preveMd5 = await isFileExisted("./lomd5.js")
    console.log(preveMd5,'成功2')
    preveMd5=require('./lomd5.js').md5
  }catch(error){
    preveMd5 = null
    console.log(error,22222)
  }
})()
console.log(content,preveMd5)

app.listen(`3300`, () => console.log(`ok,3300`));
// 查找全部
app.get("/get/all",function(req,res){
  if(content==null){
    res.send(['你还没存储过任何东西'])
  }else{
    let arrAll=[]
    for(let i in content){
      arrAll.push({[i]:content[i]})
    }
    res.send(arrAll)
  }
})
// 查找
app.get("/get", function (req, res) {
  console.log(content)
  if(content==null){
    res.send('你还没储存过任何东西')
    return
  }
  let arr=Object.getOwnPropertyNames(content)
if(!arr.length){
  res.send('空空如也，赶紧添加吧')
    return
}
  console.log(req.query.key);
  let select = req.query.key;
  let arrs=[];
  Object.keys(content).forEach(v=>{
    if(v.indexOf(select)!=-1){
      arrs.push(`${v}---${content[v]}`)
    }
  })
  if(arrs.length){
  res.send(arrs);
  }else{
    res.send('在您的字典了寻找不到呀')
  }
});
// 存储
app.get("/set", function (req, res) {
  if (content!=null) {
     newContent = JSON.stringify({ ...content, ...req.query });
  } else {
    newContent = JSON.stringify({ ...req.query });
  }
  fs.writeFile(
    "./content.js",
    "module.exports=" + newContent,
    "utf-8",
    function (err, data) {}
  );
  console.log(newContent)

  fs.watch(
    "./content.js",
    { persistent: true, interval: 500 },
    function (a, b) {
      let currentMd5 = md5(fs.readFileSync("./content.js"));
      console.log(currentMd5,preveMd5)
      if (currentMd5 == preveMd5) {
        res.send("毫无变化");
        return;
      }
      preveMd5 = JSON.stringify({ md5: currentMd5 });
      fs.writeFile(
        "./lomd5.js",
        "module.exports=" + preveMd5,
        "utf-8",
        function (err, data) {}
      );
      res.send("储存成功");
    }
  );
});


// 判断文件是否存在
function isFileExisted(fileName){
  return new Promise(function(resolve,reject){
    fs.access(fileName,(err)=>{
      if(err){
        reject(err.message);
      }else{
        resolve('existed')
      }
    })
  })
}
